package com.luoyuanxiangvip.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * @author: luoyuanxiang
 * @className: SpringUtil
 * @packageName: com.luoyuanxiangvip.common.utils
 * @description: 获取实体bean
 * @data: 2019/5/25 21:03
 **/
@Slf4j
@Component
public class SpringUtil implements ApplicationContextAware {

    private static ApplicationContext context;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        synchronized (SpringUtil.class) {
            context = applicationContext;
            SpringUtil.class.notifyAll();
        }
    }

    /**
     * 获取applicationContext
     */
    private static void getApplicationContext() {
        synchronized (SpringUtil.class) {
            while (context == null) {
                try {
                    SpringUtil.class.wait(20000);
                    if (context == null) {
                        log.warn("请等待ApplicationContext的生成。");
                    }
                } catch (InterruptedException e) {
                    log.error("ApplicationContext获取失败>>", e);
                }
            }
        }
    }

    /**
     * 通过name获取 Bean
     * @param name bean 名称
     * @return Object
     */
    public static Object getBean(String name){
        getApplicationContext();
        return context.getBean(name);
    }

    /**
     * 通过class获取Bean.
     * @param clazz 类
     * @param <T> 类
     * @return 对象
     */
    public static <T> T getBean(Class<T> clazz){
        getApplicationContext();
        return context.getBean(clazz);
    }

    /**
     * 通过name,以及Clazz返回指定的Bean
     * @param name 名称
     * @param clazz 类
     * @param <T> 类
     * @return 类
     */
    public static <T> T getBean(String name,Class<T> clazz){
        getApplicationContext();
        return context.getBean(name, clazz);
    }
}
